<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>OpenLayers example</title>
  <link rel="stylesheet" href="libs/v6.5.0/css/ol.css" type="text/css">
  <link rel="stylesheet" href="libs/v6.5.0/examples/resources/layout.css" type="text/css">
  <link rel="stylesheet" href="libs/ol-layerswitcher/dist/ol-layerswitcher.css" />

  <script src="libs/v6.5.0/build/ol.js"></script>
  <script src="libs/ol-layerswitcher/dist/ol-layerswitcher.js"></script>
  <script src="libs/jquery.min.js"></script>

  <link rel="stylesheet" href="libs/jquery-ui-1.12.1/jquery-ui.css">
  <script src="libs/jquery-ui-1.12.1/external/jquery/jquery.js"></script>
  <script src="libs/jquery-ui-1.12.1/jquery-ui.js"></script>

  <link rel="stylesheet" href="libs/bootstrap.min.css">
  <script type="text/javascript" src="libs/bootstrap.min.js"></script>

  <style>
    html,
    body {
      height: 100%;
      padding: 0;
      margin: 0;
      font-family: arial;
    }

    #title {
      position: absolute;
      top: 0%;
      left: 0%;
      width: 100%;
      height: 4%;
      background-color: #f1f3f4;
      border: 1px solid darkgrey;
    }

    #map {
      position: absolute;
      top: 4%;
      left: 20%;
      width: 80%;
      height: 96%;
      overflow: scroll;
      border: 0.5px solid #4CAF50;
    }

    #wms_layers_btn {
      position: absolute;
      z-index: 500;
      top: 1%;
      left: 60%;
    }

    #data {
      width: 60%;
    }

    #table_data {
      position: absolute;
      bottom: 0%;
      overflow: scroll;
      left: 20%;
      right: 0%;
      height: 0%;
      border: 1px solid #4CAF50;
    }

    #table {
      white-space: nowrap;
      grid-template-areas: "head-fixed""body-scrollable";
    }

    #showData {
      overflow: auto;
      width: 100%;
    }


    #table th {
      position: -webkit-sticky;
      /* for Safari */
      position: sticky;
      top: 0;
      background-color: darksalmon;
    }

    #table_wms_layers {

      white-space: nowrap;
      border-collapse: separate;
      font-family: arial;
      font-size: 14px;

    }

    #table_wms_layers th {
      position: -webkit-sticky;
      /* for Safari */
      position: sticky;
      top: 0;
      background-color: darksalmon;
    }

    #clear_btn {
      position: absolute;
      z-index: 500;
      top: 1%;
      left: 75%;

    }

    .ol-mouse-position {
      top: 97%;
      right: 20%;
      position: absolute;
      font-weight: bold;
    }

    .layer-switcher.shown {
      max-height: 465px;
    }

    #query_tab {
      position: absolute;
      padding: 0.5% 0%;
      top: 4%;
      height: 58%;
      overflow: scroll;
      width: 20%;
      left: 0%;

    }

    .tab-content {
      position: relative;
      top: 1%;
      width: 85%;
      height: 85%;
      /* overflow: scroll;
      border: 1px solid blue; */
    }

    #legend {
      z-index: 11;
      padding: 2px 4px;
      border: 1px solid grey;
      position: absolute;
      bottom: 0%;
      height: 38%;
      overflow: scroll;
      width: 20%;
      left: 0%;
      background-color: #ffffff;
      font-weight: bold;
    }

    .ol-popup {
      position: absolute;
      background-color: white;
      -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
      filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
      padding: 15px;
      border-radius: 10px;
      border: 1px solid #cccccc;
      bottom: 12px;
      left: -50px;
      min-width: 280px;
    }

    .ol-popup:after,
    .ol-popup:before {
      top: 100%;
      border: solid transparent;
      content: " ";
      height: 0;
      width: 0;
      position: absolute;
      pointer-events: none;
    }

    .ol-popup:after {
      border-top-color: white;
      border-width: 10px;
      left: 48px;
      margin-left: -10px;
    }

    .ol-popup:before {
      border-top-color: #cccccc;
      border-width: 11px;
      left: 48px;
      margin-left: -11px;
    }

    .ol-popup-closer {
      text-decoration: none;
      position: absolute;
      top: 2px;
      right: 8px;
    }

    .ol-popup-closer:after {
      content: "X";
    }

    #measure {
      position: absolute;
      z-index: 50;
      top: 1%;
      /* height:1%; */
      left: 5%;

    }

    #getinfo {
      position: absolute;
      z-index: 50;
      top: 1%;
      /* height:15px; */
      left: 30%;

    }

    .tooltip {
      position: relative;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 4px;
      color: white;
      padding: 4px 8px;
      opacity: 0.7;
      white-space: nowrap;
    }

    .tooltip-measure {
      opacity: 1;
      font-weight: bold;
    }

    .tooltip-static {
      background-color: #ffcc33;
      color: black;
      border: 1px solid white;
    }

    .tooltip-measure:before,
    .tooltip-static:before {
      border-top: 6px solid rgba(0, 0, 0, 0.5);
      border-right: 6px solid transparent;
      border-left: 6px solid transparent;
      content: "";
      position: absolute;
      bottom: -6px;
      margin-left: -7px;
      left: 50%;
    }

    .tooltip-static:before {
      border-top-color: #ffcc33;
    }
  </style>
  <style>
    button.btn-settings {
      margin: 25px;
      padding: 20px 30px;
      font-size: 1.2em;
      background-color: #337ab7;
      color: white;
    }

    button.btn-settings:active {
      color: white;
    }

    .modal {
      overflow: hidden;
    }

    .modal-dialog {
      height: 300px;
    }

    .modal-header {
      height: 30px;
      padding: 20px;
      background-color: #18456b;
      color: white;
    }

    .modal-title {
      margin-top: -10px;
      font-size: 16px;
    }

    .modal-header .close {
      margin-top: -10px;
      color: #fff;
    }

    .modal-body {
      color: #888;
      padding: 5px 35px 20px;
    }

    .modal-body h3 {
      text-align: center;
    }

    .modal-body p {
      padding-top: 10px;
      font-size: 1.1em;
    }
  </style>
</head>

<body>
  <div id="title">
    <marquee behavior="scroll" direction="left">
      <h5><b>基于Web的GIS应用</b></h5>
    </marquee>
  </div>
  <div id="map">
    <form id="measure">
      <label>测量类型 &nbsp;</label>
      <select id="measuretype">
        <option value="select">选择测量选项</option>
        <option value="length">长度 (LineString)</option>
        <option value="area">面积 (Polygon)</option>
        <option value="clear">清除测量</option>
      </select>
    </form>
    <form id="getinfo">
      <label>获取要素信息&nbsp;</label>
      <select id="getinfotype">
        <option value="select">选择选项</option>
        <option value="activate_getinfo">激活获取</option>
        <option value="deactivate_getinfo">停止获取</option>
      </select>
    </form>
    <button onclick="wms_layers()" id="wms_layers_btn">可用的WMS图层</button>
    <button onclick="clear_all()" id="clear_btn">清除</button>
  </div>

  <div id="popup" class="ol-popup">
    <a href="#" id="popup-closer" class="ol-popup-closer"></a>
    <div id="popup-content"></div>
  </div>
  <div id="info">&nbsp;</div>

  <div id="legend"></div>
  <div id="query_tab">
    <ul class="nav nav-tabs">
      <li class="active"><a data-toggle="tab" href="#form">按属性选择</a></li>
      <li><a data-toggle="tab" href="#form1">按绘图选择</a></li>
    </ul>

    <div class="tab-content">
      <div id="form" class="tab-pane fade in active">
        <label for="layer">选择图层</label>
        <select class="form-control" id="layer" name="layer">
          <option value="">选择图层</option>
        </select>
        <br>
        <label for="attributes">选择属性</label>
        <select class="form-control" id="attributes" name="attributes">
          <option value="">选择属性</option>
        </select>
        <br>
        <label for="operator">选择运输符</label>
        <select class="form-control" id="operator" name="operator">
          <option value="">选择运输符</option>
        </select>
        <br>

        <label for="value">输入值</label>
        <input type="text" class="form-control" id="value" name="value">
        <br>
        <button class="btn btn-success" onclick="query()">查询</button>
      </div>
      <div id="form1" class="tab-pane fade">
        <label for="layer1">选择图层</label>
        <select class="form-control" id="layer1" name="layer1">
          <option value="">选择图层</option>
        </select>
        <br>
        <label for="attributes">选择属性</label>

        <label for="draw_type">几何图形类型 &nbsp;</label>
        <select class="form-control" id="draw_type" name="draw_type">
          <option value="select">选择形状</option>
          <option value="Square">正方形</option>
          <option value="Box">长方形</option>
          <option value="Polygon">多边形</option>
          <option value="Star">星形</option>
          <option value="clear">清除</option>
        </select>
        <br>
      </div>
    </div>

  </div>
  <div id="table_data"> </div>
  <div id="wms_layers_window" title="可用的WMS图层" style="display:none"></div>
  <table id="table_wms_layers" class="table-bordered">
  </table>

  <script type="text/javascript">
    var map, geojson, layer_name, layerSwitcher, featureOverlay;
    var container, content, closer;

    //geoserver路径
    var geoserverURL='http://localhost:8085';

    var container = document.getElementById('popup');
    var content = document.getElementById('popup-content');
    var closer = document.getElementById('popup-closer');

    /**
     * 创建覆盖以将弹出窗口锚定到地图.
     */
    var overlay = new ol.Overlay({
      element: container,
      autoPan: true,
      autoPanAnimation: {
        duration: 250
      }
    });

    /**
     * 添加单击处理程序以隐藏弹出窗口.
     * @return {boolean} Don't follow the href.
     */
    closer.onclick = function () {
      overlay.setPosition(undefined);
      closer.blur();
      return false;
    };

    var view = new ol.View({
      projection: 'EPSG:4326',
      center: [-73.97, 40.77],
      zoom: 13,
    });
    var view_ov = new ol.View({
      projection: 'EPSG:4326',
      center: [-73.97, 40.77],
      zoom: 13,
    });

    var base_maps = new ol.layer.Group({
      'title': '基础地图',
      layers: [
        new ol.layer.Tile({
          title: 'OSM',
          type: 'base',
          visible: true,
          source: new ol.source.OSM()
        })
      ]
    });

    var OSM = new ol.layer.Tile({
      source: new ol.source.OSM(),
      type: 'base',
      title: 'OSM',
    });

    var overlays = new ol.layer.Group({
      'title': '图层',
      layers: [
        new ol.layer.Image({
          title: 'poly_landmarks',
          // extent: [-180, -90, -180, 90],
          source: new ol.source.ImageWMS({
            url: geoserverURL+'/geoserver/wms',
            params: { 'LAYERS': 'tiger:poly_landmarks' },

            ratio: 1,
            serverType: 'geoserver'
          })
        }),
        new ol.layer.Image({
          title: 'tiger_roads',
          // extent: [-180, -90, -180, 90],
          source: new ol.source.ImageWMS({
            url: geoserverURL+'/geoserver/wms',
            params: { 'LAYERS': 'tiger:tiger_roads' },
            ratio: 1,
            serverType: 'geoserver'
          })
        })
      ]
    });

    var map = new ol.Map({
      target: 'map',
      view: view,
      overlays: [overlay]
    });

    map.addLayer(base_maps);
    map.addLayer(overlays);

    var rainfall = new ol.layer.Image({
      title: 'poi',
      // extent: [-180, -90, -180, 90],
      source: new ol.source.ImageWMS({
        url: geoserverURL+'/geoserver/wms',
        params: { 'LAYERS': 'tiger:poi' },
        ratio: 1,
        serverType: 'geoserver'
      })
    });

    overlays.getLayers().push(rainfall);
    var mouse_position = new ol.control.MousePosition();
    map.addControl(mouse_position);
    var overview = new ol.control.OverviewMap({
      view: view_ov,
      collapseLabel: 'O',
      label: 'O',
      layers: [OSM]
    });

    map.addControl(overview);

    var full_sc = new ol.control.FullScreen({ label: 'F' });
    map.addControl(full_sc);

    var zoom = new ol.control.Zoom({ zoomInLabel: '+', zoomOutLabel: '-' });
    map.addControl(zoom);

    var slider = new ol.control.ZoomSlider();
    map.addControl(slider);

    var zoom_ex = new ol.control.ZoomToExtent({
      extent: [
        65.90, 7.48,
        98.96, 40.30
      ]
    });
    map.addControl(zoom_ex);

    var layerSwitcher = new ol.control.LayerSwitcher({
      activationMode: 'click',
      startActive: true,
      tipLabel: 'Layers', // 按钮的可选标签
      groupSelectStyle: 'children', // Can be 'children' [default], 'group' or 'none'
      collapseTipLabel: 'Collapse layers',
    });
    map.addControl(layerSwitcher);

    function legend() {
      $('#legend').empty();
      var no_layers = overlays.getLayers().get('length');
      var head = document.createElement("h4");
      var txt = document.createTextNode("图例");
      head.appendChild(txt);
      var element = document.getElementById("legend");
      element.appendChild(head);
      var ar = [];
      var i;
      for (i = 0; i < no_layers; i++) {
        ar.push(geoserverURL+"/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=" + overlays.getLayers().item(i).get('title'));
      }
      for (i = 0; i < no_layers; i++) {
        var head = document.createElement("p");
        var txt = document.createTextNode(overlays.getLayers().item(i).get('title'));
        head.appendChild(txt);
        var element = document.getElementById("legend");
        element.appendChild(head);
        var img = new Image();
        img.src = ar[i];
        var src = document.getElementById("legend");
        src.appendChild(img);
      }
    }
    legend();

    function getinfo(evt) {
      var coordinate = evt.coordinate;
      var viewResolution = /** @type {number} */ (view.getResolution());
      $("#popup-content").empty();
      document.getElementById('info').innerHTML = '';
      var no_layers = overlays.getLayers().get('length');
      var url = new Array();
      var wmsSource = new Array();
      var layer_title = new Array();
      var i;
      for (i = 0; i < no_layers; i++) {
        var visibility = overlays.getLayers().item(i).getVisible();
        if (visibility == true) {
          layer_title[i] = overlays.getLayers().item(i).get('title');
          wmsSource[i] = new ol.source.ImageWMS({
            url: geoserverURL+'/geoserver/wms',
            params: { 'LAYERS': layer_title[i] },
            serverType: 'geoserver',
            crossOrigin: 'anonymous'
          });
          url[i] = wmsSource[i].getFeatureInfoUrl(
            evt.coordinate, viewResolution, 'EPSG:4326',
            { 'INFO_FORMAT': 'text/html' });
          $.get(url[i], function (data) {
            $("#popup-content").append(data);
            overlay.setPosition(coordinate);
            layerSwitcher.renderPanel();
          });
        }
      }
    }

    getinfotype.onchange = function () {
      map.removeInteraction(draw);
      if (vectorLayer) { vectorLayer.getSource().clear(); }
      map.removeOverlay(helpTooltip);
      if (measureTooltipElement) {
        var elem = document.getElementsByClassName("tooltip tooltip-static");
        for (var i = elem.length - 1; i >= 0; i--) {
          elem[i].remove();
        }
      }
      if (getinfotype.value == 'activate_getinfo') {
        map.on('singleclick', getinfo);
      }
      else if (getinfotype.value == 'select' || getinfotype.value == 'deactivate_getinfo') {
        map.un('singleclick', getinfo);
        overlay.setPosition(undefined);
        closer.blur();
      }
    };

    // measure tool
    var source = new ol.source.Vector();
    var vectorLayer = new ol.layer.Vector({
      //title: 'layer',
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new ol.style.Stroke({
          color: '#ffcc33',
          width: 2
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#ffcc33'
          })
        })
      })
    });
    map.addLayer(vectorLayer);

    /**
       * 当前绘制的要素.
       * @type {module:ol/Feature~Feature}
       */
    var sketch;


    /**
     * 帮助工具提示元素.
     * @type {Element}
     */
    var helpTooltipElement;


    /**
     * 覆盖以显示帮助消息.
     * @type {module:ol/Overlay}
     */
    var helpTooltip;


    /**
     * 度量工具提示元素.
     * @type {Element}
     */
    var measureTooltipElement;


    /**
     * 叠加显示测量值.
     * @type {module:ol/Overlay}
     */
    var measureTooltip;


    /**
     * 用户绘制多边形时显示的消息.
     * @type {string}
     */
    var continuePolygonMsg = '单击以继续绘制多边形';


    /**
     * Message to show when the user is drawing a line.
     * @type {string}
     */
    var continueLineMsg = '单击以继续绘制多边线';


    /**
     * 手柄指针移动.
     * @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt The event.
     */
    var pointerMoveHandler = function (evt) {
      if (evt.dragging) {
        return;
      }
      /** @type {string} */
      var helpMsg = 'Click to start drawing';

      if (sketch) {
        var geom = (sketch.getGeometry());
        if (geom instanceof ol.geom.Polygon) {

          helpMsg = continuePolygonMsg;
        } else if (geom instanceof ol.geom.LineString) {
          helpMsg = continueLineMsg;
        }
      }

      helpTooltipElement.innerHTML = helpMsg;
      helpTooltip.setPosition(evt.coordinate);

      helpTooltipElement.classList.remove('hidden');
    };

    map.on('pointermove', pointerMoveHandler);

    map.getViewport().addEventListener('mouseout', function () {
      helpTooltipElement.classList.add('hidden');
    });

    //var measuretype = document.getElementById('measuretype');

    var draw; // global so we can remove it later


    /**
     * 格式长度输出.
     * @param {module:ol/geom/LineString~LineString} line The line.
     * @return {string} The formatted length.
     */
    var formatLength = function (line) {
      var length = ol.sphere.getLength(line, { projection: 'EPSG:4326' });
      var output;
      if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
          ' ' + 'km';
      } else {
        output = (Math.round(length * 100) / 100) +
          ' ' + 'm';
      }
      return output;

    };

    /**
     * 格式面积输出.
     * @param {module:ol/geom/Polygon~Polygon} polygon The polygon.
     * @return {string}// Formatted area.
     */
    var formatArea = function (polygon) {
      var area = ol.sphere.getArea(polygon, { projection: 'EPSG:4326' });
      var output;
      if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
          ' ' + 'km<sup>2</sup>';
      } else {
        output = (Math.round(area * 100) / 100) +
          ' ' + 'm<sup>2</sup>';
      }
      return output;
    };

    function addInteraction() {
      var type;
      if (measuretype.value == 'area') { type = 'Polygon'; }
      else if (measuretype.value == 'length') { type = 'LineString'; }

      //var type = (measuretype.value == 'area' ? 'Polygon' : 'LineString');
      draw = new ol.interaction.Draw({
        source: source,
        type: type,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.5)'
          }),
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            lineDash: [10, 10],
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 5,
            stroke: new ol.style.Stroke({
              color: 'rgba(0, 0, 0, 0.7)'
            }),
            fill: new ol.style.Fill({
              color: 'rgba(255, 255, 255, 0.5)'
            })
          })
        })
      });

      if (measuretype.value == 'select' || measuretype.value == 'clear') {
        map.removeInteraction(draw);
        if (vectorLayer) { vectorLayer.getSource().clear(); }
        map.removeOverlay(helpTooltip);
        if (measureTooltipElement) {
          var elem = document.getElementsByClassName("tooltip tooltip-static");
          //$('#measure_tool').empty(); 
          for (var i = elem.length - 1; i >= 0; i--) {
            elem[i].remove();
          }
        }
        //var elem1 = elem[0].innerHTML;

      }
      else if (measuretype.value == 'area' || measuretype.value == 'length') {
        map.addInteraction(draw);
        createMeasureTooltip();
        createHelpTooltip();
        var listener;
        draw.on('drawstart',
          function (evt) {
            // 设置草图

            sketch = evt.feature;

            /** @type {module:ol/coordinate~Coordinate|undefined} */
            var tooltipCoord = evt.coordinate;

            listener = sketch.getGeometry().on('change', function (evt) {
              var geom = evt.target;
              var output;
              if (geom instanceof ol.geom.Polygon) {
                output = formatArea(geom);
                tooltipCoord = geom.getInteriorPoint().getCoordinates();

              } else if (geom instanceof ol.geom.LineString) {
                output = formatLength(geom);
                tooltipCoord = geom.getLastCoordinate();
              }
              measureTooltipElement.innerHTML = output;
              measureTooltip.setPosition(tooltipCoord);
            });
          }, this);

        draw.on('drawend',
          function () {
            measureTooltipElement.className = 'tooltip tooltip-static';
            measureTooltip.setOffset([0, -7]);
            // 未设置草图
            sketch = null;
            // 取消设置工具提示以便可以创建新的工具提示
            measureTooltipElement = null;
            createMeasureTooltip();
            ol.Observable.unByKey(listener);
          }, this);

      }
    }

    /**
     * 创建新的帮助工具提示
     */
    function createHelpTooltip() {
      if (helpTooltipElement) {
        helpTooltipElement.parentNode.removeChild(helpTooltipElement);
      }
      helpTooltipElement = document.createElement('div');
      helpTooltipElement.className = 'tooltip hidden';
      helpTooltip = new ol.Overlay({
        element: helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
      });
      map.addOverlay(helpTooltip);
    }

    /**
     * 创建新的度量工具提示
     */
    function createMeasureTooltip() {
      if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
      }
      measureTooltipElement = document.createElement('div');
      measureTooltipElement.className = 'tooltip tooltip-measure';
      measureTooltip = new ol.Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center'
      });
      map.addOverlay(measureTooltip);

    }


    /**
     * 允许用户更改几何图形类型
     */
    measuretype.onchange = function () {
      map.un('singleclick', getinfo);
      overlay.setPosition(undefined);
      closer.blur();
      map.removeInteraction(draw);
      addInteraction();
    };

    // wms图层窗口
    function wms_layers() {
      $(function () {
        $("#wms_layers_window").dialog({
          height: 400,
          width: 800,
          modal: true
        });
        $("#wms_layers_window").show();
      });
      $(document).ready(function () {
        $.ajax({
          type: "GET",
          url: geoserverURL+"/geoserver/wms?request=getCapabilities",
          dataType: "xml",
          success: function (xml) {
            $('#table_wms_layers').empty();
            console.log("here");
            $('<tr></tr>').html('<th>Name</th><th>Title</th><th>Abstract</th>').appendTo('#table_wms_layers');
            $(xml).find('Layer').find('Layer').each(function () {
              var name = $(this).children('Name').text();
              //var name1 = name.find('Name').text();
             
              var title = $(this).children('Title').text();

              var abst = $(this).children('Abstract').text();
              $('<tr></tr>').html('<td>' + name + '</td><td>' + title + '</td><td>' + abst + '</td>').appendTo('#table_wms_layers');
            });
            addRowHandlers();
          }
        });
      });

      var divContainer = document.getElementById("wms_layers_window");
      var table1 = document.getElementById("table_wms_layers");
      divContainer.innerHTML = "";
      divContainer.appendChild(table1);
      $("#wms_layers_window").show();
      var add_map_btn = document.createElement("BUTTON");
      add_map_btn.setAttribute("id", "add_map_btn");
      add_map_btn.innerHTML = "添加图层到地图";
      add_map_btn.setAttribute("onclick", "add_layer()");
      divContainer.appendChild(add_map_btn);

      /*	function findRowNumber(cn1, v1){
      var table = document.querySelector('#table1');
      var rows = table.querySelectorAll("tr");
      var msg = "No such row exist"
      for(i=1;i<rows.length;i++){
        var tableData = rows[i].querySelectorAll("td");
        if(tableData[cn1-1].textContent==v1){
          msg = i;
          break;
        }
      }
      return msg;
    }
    */

      function addRowHandlers() {
        var rows = document.getElementById("table_wms_layers").rows;
        var table = document.getElementById('table_wms_layers');
        var heads = table.getElementsByTagName('th');
        var col_no;
        for (var i = 0; i < heads.length; i++) {
          var head = heads[i];
          if (head.innerHTML == 'Name') {
            col_no = i + 1;
          }
        }
        for (i = 0; i < rows.length; i++) {
          rows[i].onclick = function () {
            return function () {
              $(function () {
                $("#table_wms_layers td").each(function () {
                  $(this).parent("tr").css("background-color", "white");
                });
              });
              var cell = this.cells[col_no - 1];
              layer_name = cell.innerHTML;
              $(document).ready(function () {
                $("#table_wms_layers td:nth-child(" + col_no + ")").each(function () {
                  if ($(this).text() == layer_name) {
                    $(this).parent("tr").css("background-color", "grey");
                  }
                });
              });
            };
          }(rows[i]);
        }
        /*$("#add_map_btn").click(function () {
            // var value = $(".selected td:first").html();
            // value = value || "No row Selected";
             alert(layer_name);
         });*/
      }

    }

    function add_layer() {
      var name = layer_name.split(":");
      var layer_wms = new ol.layer.Image({
        title: name[1],
        // extent: [-180, -90, -180, 90],
        source: new ol.source.ImageWMS({
          url: geoserverURL+'/geoserver/wms',
          params: { 'LAYERS': layer_name },
          ratio: 1,
          serverType: 'geoserver'
        })
      });
      overlays.getLayers().push(layer_wms);
      var url = geoserverURL+'/geoserver/wms?request=getCapabilities';
      var parser = new ol.format.WMSCapabilities();

      $.ajax(url).then(function (response) {
        var result = parser.read(response);
        var Layers = result.Capability.Layer.Layer;
        var extent;
        for (var i = 0, len = Layers.length; i < len; i++) {
          var layerobj = Layers[i];
          if (layerobj.Name == layer_name) {
            extent = layerobj.BoundingBox[0].extent;
            map.getView().fit(
              extent,
              { duration: 1590, size: map.getSize() }
            );
          }
        }
      });
      /*layer_wms.getSource().on('singleclick', function(){
      map.getView().fit(
          layer_wms.getExtent(),
          { duration: 1590, size: map.getSize() }
      );
   });*/

      layerSwitcher.renderPanel();
      legend();
    }

    // layers_name
    $(document).ready(function () {
      $.ajax({
        type: "GET",
        url: geoserverURL+"/geoserver/wfs?request=getCapabilities",
        dataType: "xml",
        success: function (xml) {
          var select = $('#layer');
          $(xml).find('FeatureType').each(function () {
            //var title = $(this).find('ows:Operation').attr('name');
            var name = $(this).find('Name').text();
            //select.append("<option/><option class='ddheader' value='"+ name +"'>"+title+"</option>");
            $(this).find('Name').each(function () {
              var value = $(this).text();
              select.append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
            });
          });
          //select.children(":first").text("please make a selection").attr("selected",true);
        }
      });
    });

    // 属性下拉列表
    $(function () {
      $("#layer").change(function () {
        var attributes = document.getElementById("attributes");
        var length = attributes.options.length;
        for (i = length - 1; i >= 0; i--) {
          attributes.options[i] = null;
        }
        var value_layer = $(this).val();

        //var level = document.getElementById("level");
        //var value_level = level.options[level.selectedIndex].value;
        // var url = geoserverURL+"/geoserver/wfs?service=WFS&request=DescribeFeatureType&version=1.1.0&typeName="+value_layer;

        attributes.options[0] = new Option('选择要素', "");
        $(document).ready(function () {
          $.ajax({
            type: "GET",
            url: geoserverURL+"/geoserver/wfs?service=WFS&request=DescribeFeatureType&version=1.1.0&typeName=" + value_layer,
            dataType: "xml",
            success: function (xml) {
              var select = $('#attributes');
              //var title = $(xml).find('xsd\\:complexType').attr('name');
              $(xml).find('xsd\\:sequence').each(function () {
                $(this).find('xsd\\:element').each(function () {
                  var value = $(this).attr('name');
                  var type = $(this).attr('type');
                  if (value != 'geom' && value != 'the_geom') {
                    select.append("<option class='ddindent' value='" + type + "'>" + value + "</option>");
                  }
                });
              });
            }
          });
        });
      });
    });

    // 运算符组合框
    $(function () {
      $("#attributes").change(function () {

        var operator = document.getElementById("operator");
        var length = operator.options.length;
        for (i = length - 1; i >= 0; i--) {
          operator.options[i] = null;
        }
        var value_type = $(this).val();
        var value_attribute = $('#attributes option:selected').text();
        operator.options[0] = new Option('选择运算符', "");
        if (value_type == 'xsd:short' || value_type == 'xsd:int' || value_type == 'xsd:double') {
          var operator1 = document.getElementById("operator");
          operator1.options[1] = new Option('大于(>)', '>');
          operator1.options[2] = new Option('小于(<)', '<');
          operator1.options[3] = new Option('等于(=)', '=');
        }
        else if (value_type == 'xsd:string') {
          var operator1 = document.getElementById("operator");
          operator1.options[1] = new Option('相似(Like)', 'ILike');
        }

      });
    });

    var highlightStyle = new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(255,255,255,0.7)',
      }),
      stroke: new ol.style.Stroke({
        color: '#3399CC',
        width: 3,
      }),
      image: new ol.style.Circle({
        radius: 10,
        fill: new ol.style.Fill({
          color: '#3399CC'
        })
      })
    });

    featureOverlay = new ol.layer.Vector({
      source: new ol.source.Vector(),
      map: map,
      style: highlightStyle
    });
    var highlight1;

    function findRowNumber(cn1, v1) {
      var table = document.querySelector('#table');
      var rows = table.querySelectorAll("tr");
      var msg = "No such row exist"
      for (i = 1; i < rows.length; i++) {
        var tableData = rows[i].querySelectorAll("td");
        if (tableData[cn1 - 1].textContent == v1) {
          msg = i;
          break;
        }
      }
      return msg;
    }

    function addRowHandlers() {
      var rows = document.getElementById("table").rows;
      var heads = table.getElementsByTagName('th');
      var col_no;
      for (var i = 0; i < heads.length; i++) {
        var head = heads[i];
        if (head.innerHTML == 'id') {
          col_no = i + 1;
        }

      }
      for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function () {
          return function () {
            featureOverlay.getSource().clear();

            $(function () {
              $("#table td").each(function () {
                $(this).parent("tr").css("background-color", "white");
              });
            });
            var cell = this.cells[col_no - 1];
            var id = cell.innerHTML;
            $(document).ready(function () {
              $("#table td:nth-child(" + col_no + ")").each(function () {
                if ($(this).text() == id) {
                  $(this).parent("tr").css("background-color", "grey");
                }
              });
            });

            var features = geojson.getSource().getFeatures();
            for (i = 0; i < features.length; i++) {
              if (features[i].getId() == id) {
                featureOverlay.getSource().addFeature(features[i]);
                featureOverlay.getSource().on('addfeature', function () {
                  map.getView().fit(
                    featureOverlay.getSource().getExtent(),
                    { duration: 1590, size: map.getSize() }
                  );
                });
              }
            }
          };
        }(rows[i]);
      }
    }

    function highlight(evt) {
      featureOverlay.getSource().clear();
      var feature = map.forEachFeatureAtPixel(evt.pixel,
        function (feature, layer) {
          return feature;
        });
      if (feature) {
        var geometry = feature.getGeometry();
        var coord = geometry.getCoordinates();
        var coordinate = evt.coordinate;
        /*var content1 = '<h3>' + feature.get([name]) + '</h3>';
        content1 += '<h5>' + feature.get('crop')+' '+ value_param +' '+ value_seas+' '+value_level+'</h5>'
    content1 += '<h5>' + feature.get([value_param]) +' '+ unit +'</h5>';
  	
        content.innerHTML = content1;
        overlay.setPosition(coordinate);*/
        $(function () {
          $("#table td").each(function () {
            $(this).parent("tr").css("background-color", "white");
          });
        });
        featureOverlay.getSource().addFeature(feature);
      }

      /*$(function() {
    $("#table td").each(function() {
      if ($(this).text() == feature.get('gid')) {
       // $(this).css('color', 'red');
       $(this).parent("tr").css("background-color", "grey");
      }
    });
  });*/
      var table = document.getElementById('table');
      var cells = table.getElementsByTagName('td');
      var rows = document.getElementById("table").rows;
      var heads = table.getElementsByTagName('th');
      var col_no;
      for (var i = 0; i < heads.length; i++) {
        var head = heads[i];
        if (head.innerHTML == 'id') {
          col_no = i + 1;
        }
      }
      var row_no = findRowNumber(col_no, feature.getId());
      var rows = document.querySelectorAll('#table tr');
      rows[row_no].scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
      $(document).ready(function () {
        $("#table td:nth-child(" + col_no + ")").each(function () {

          if ($(this).text() == feature.getId()) {
            $(this).parent("tr").css("background-color", "grey");
          }
        });
      });
    };

    function query() {
      $('#table').empty();
      if (geojson) {
        map.removeLayer(geojson);
      }
      if (featureOverlay) {
        featureOverlay.getSource().clear();
        map.removeLayer(featureOverlay);
      }
      var layer = document.getElementById("layer");
      var value_layer = layer.options[layer.selectedIndex].value;
      var attribute = document.getElementById("attributes");
      var value_attribute = attribute.options[attribute.selectedIndex].text;
      var operator = document.getElementById("operator");
      var value_operator = operator.options[operator.selectedIndex].value;
      var txt = document.getElementById("value");
      var value_txt = txt.value;
      if (value_operator == 'ILike') {
        value_txt = "" + value_txt + "%25";
        //value_attribute = 'strToLowerCase('+value_attribute+')';
      }
      else {
        value_txt = value_txt;
        //value_attribute = value_attribute;
      }

      var url = geoserverURL+"/geoserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=" + value_layer + "&CQL_FILTER=" + value_attribute + "+" + value_operator + "+'" + value_txt + "'&outputFormat=application/json"
      var style = new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.7)'
        }),
        stroke: new ol.style.Stroke({
          color: '#ffcc33',
          width: 3
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#ffcc33'
          })
        })
      });


      geojson = new ol.layer.Vector({
        //title:'dfdfd',
        //title: '<h5>' + value_crop+' '+ value_param +' '+ value_seas+' '+value_level+'</h5>',
        source: new ol.source.Vector({
          url: url,
          format: new ol.format.GeoJSON()
        }),
        style: style,
      });

      geojson.getSource().on('addfeature', function () {
        map.getView().fit(
          geojson.getSource().getExtent(),
          { duration: 1590, size: map.getSize() }
        );
      });
      map.addLayer(geojson);

      $.getJSON(url, function (data) {
        //alert(data.features[0].properties);
        //alert(data.features.length);
        var col = [];
        col.push('id');
        for (var i = 0; i < data.features.length; i++) {

          for (var key in data.features[i].properties) {

            if (col.indexOf(key) === -1) {
              col.push(key);
            }
          }
        }

        var table = document.createElement("table");
        table.setAttribute("class", "table table-bordered");
        table.setAttribute("id", "table");
        // 使用上面提取的标题创建HTML表格标题行

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
          var th = document.createElement("th");      // TABLE HEADER.
          th.innerHTML = col[i];
          tr.appendChild(th);
        }

        //将JSON数据作为行添加到表中.
        for (var i = 0; i < data.features.length; i++) {

          tr = table.insertRow(-1);

          for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            if (j == 0) { tabCell.innerHTML = data.features[i]['id']; }
            else {
              tabCell.innerHTML = data.features[i].properties[col[j]];
            }
          }
        }



        // 最后，将新创建的包含JSON数据的表添加到容器中
        var divContainer = document.getElementById("table_data");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
        addRowHandlers();

        document.getElementById('map').style.height = '71%';
        document.getElementById('table_data').style.height = '25%';
        //map.updateSize();
      });

      map.on('click', highlight);
      addRowHandlers();
    }

    // 绘制图层下拉列表
    $(document).ready(function () {
      $.ajax({
        type: "GET",
        url: geoserverURL+"/geoserver/wfs?request=getCapabilities",
        dataType: "xml",
        success: function (xml) {
          var select = $('#layer1');
          $(xml).find('FeatureType').each(function () {
            //var title = $(this).find('ows:Operation').attr('name');
            //alert(title);
            var name = $(this).find('Name').text();
            //select.append("<option/><option class='ddheader' value='"+ name +"'>"+title+"</option>");
            $(this).find('Name').each(function () {
              var value = $(this).text();
              select.append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
            });
          });
          //select.children(":first").text("please make a selection").attr("selected",true);
        }
      });
    });


    // 绘制形状
    var source1 = new ol.source.Vector({ wrapX: false });

    var vector1 = new ol.layer.Vector({
      source: source1
    });
    map.addLayer(vector1);
    var draw_typeSelect = document.getElementById('draw_type');

    var draw1; // 全局，以便我们稍后删除它
    function add_draw_Interaction() {
      var value = draw_typeSelect.value;
      //alert(value);
      if (value !== 'None') {
        var geometryFunction;
        if (value === 'Square') {
          value = 'Circle';
          geometryFunction = new ol.interaction.Draw.createRegularPolygon(4);
        } else if (value === 'Box') {
          value = 'Circle';
          geometryFunction = new ol.interaction.Draw.createBox();
        } else if (value === 'Star') {
          value = 'Circle';
          geometryFunction = function (coordinates, geometry) {
            var center = coordinates[0];
            var last = coordinates[1];
            var dx = center[0] - last[0];
            var dy = center[1] - last[1];
            var radius = Math.sqrt(dx * dx + dy * dy);
            var rotation = Math.atan2(dy, dx);
            var newCoordinates = [];
            var numPoints = 12;
            for (var i = 0; i < numPoints; ++i) {
              var angle = rotation + i * 2 * Math.PI / numPoints;
              var fraction = i % 2 === 0 ? 1 : 0.5;
              var offsetX = radius * fraction * Math.cos(angle);
              var offsetY = radius * fraction * Math.sin(angle);
              newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
            }
            newCoordinates.push(newCoordinates[0].slice());
            if (!geometry) {
              geometry = new ol.geom.Polygon([newCoordinates]);
            } else {
              geometry.setCoordinates([newCoordinates]);
            }
            return geometry;
          };
        }
        draw1 = new ol.interaction.Draw({
          source: source1,
          type: value,
          geometryFunction: geometryFunction
        });
        // map.addInteraction(draw1);

        if (draw_typeSelect.value == 'select' || draw_typeSelect.value == 'clear') {
          map.removeInteraction(draw1);
          vector1.getSource().clear();
          if (geojson) { geojson.getSource().clear(); map.removeLayer(geojson); }
        }
        else if (draw_typeSelect.value == 'Square' || draw_typeSelect.value == 'Polygon' || draw_typeSelect.value == 'Circle' || draw_typeSelect.value == 'Star' || draw_typeSelect.value == 'Box') {
          map.addInteraction(draw1);
          draw1.on('drawstart', function (evt) {
            if (vector1) { vector1.getSource().clear(); }
            if (geojson) { geojson.getSource().clear(); map.removeLayer(geojson); }
          });

          draw1.on('drawend', function (evt) {
            var feature = evt.feature;
            var coords = feature.getGeometry();
            var format = new ol.format.WKT();
            var wkt = format.writeGeometry(coords);
            var layer_name = document.getElementById("layer1");
            var value_layer = layer_name.options[layer_name.selectedIndex].value;

            var url = geoserverURL+"/geoserver/wfs?request=GetFeature&version=1.0.0&typeName=" + value_layer + "&outputFormat=json&cql_filter=INTERSECTS(the_geom," + wkt + ")";
            /*var style = new ol.style.Style({
                    fill: new ol.style.Fill({
                      color: 'rgba(255, 255, 255, 0.7)'
                    }),
                    stroke: new ol.style.Stroke({
                      color: '#ffcc33',
                      width: 3
                    }),
                
                    image: new ol.style.Circle({
                      radius: 7,
                      fill: new ol.style.Fill({
                        color: '#ffcc33'
                      })
                    })
                  });*/

            var style = new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.7)'
              }),
              stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 3
              }),
              image: new ol.style.Icon({
                anchor: [0.5, 46],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                src: 'img/marker.png',
              }),
              /*image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                  color: '#ffcc33'
                })
              })*/
            });

            geojson = new ol.layer.Vector({

              //title: '<h5>' + value_crop+' '+ value_param +' '+ value_seas+' '+value_level+'</h5>',
              source: new ol.source.Vector({
                url: url,

                format: new ol.format.GeoJSON()
              }),
              style: style,

            });

            geojson.getSource().on('addfeature', function () {
              map.getView().fit(
                geojson.getSource().getExtent(),
                { duration: 1590, size: map.getSize() }
              );
            });

            //overlays.getLayers().push(geojson);
            map.addLayer(geojson);
            map.removeInteraction(draw1);
            $.getJSON(url, function (data) {
              var col = [];
              col.push('id');
              for (var i = 0; i < data.features.length; i++) {
                for (var key in data.features[i].properties) {
                  if (col.indexOf(key) === -1) {
                    col.push(key);
                  }
                }
              }

              var table = document.createElement("table");
              table.setAttribute("class", "table table-bordered");
              table.setAttribute("id", "table");
              //使用上面提取的标题创建HTML表格标题行。

              var tr = table.insertRow(-1);                   // TABLE ROW.

              for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");      // TABLE HEADER.
                th.innerHTML = col[i];
                tr.appendChild(th);
              }

              // 将JSON数据作为行添加到表中
              for (var i = 0; i < data.features.length; i++) {

                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                  var tabCell = tr.insertCell(-1);
                  if (j == 0) { tabCell.innerHTML = data.features[i]['id']; }
                  else {
                    tabCell.innerHTML = data.features[i].properties[col[j]];
                  }
                }
              }

              //最后，将新创建的包含JSON数据的表添加到容器中
              var divContainer = document.getElementById("table_data");
              divContainer.innerHTML = "";
              divContainer.appendChild(table);
              addRowHandlers();
              document.getElementById('map').style.height = '71%';
              document.getElementById('table_data').style.height = '25%';
              map.updateSize();
            });
            map.on('click', highlight);
            addRowHandlers();
          });
        }
      }
    }

    /**
     * 处理更改事件。
     */
    draw_typeSelect.onchange = function () {
      map.removeInteraction(draw1);
      //	if (draw2) {map.removeInteraction(draw2)};
      if (draw) { map.removeInteraction(draw); map.removeOverlay(helpTooltip); map.removeOverlay(measureTooltip); }
      if (vectorLayer) { vectorLayer.getSource().clear(); }
      if (vector1) { vector1.getSource().clear(); }

      if (measureTooltipElement) {
        var elem = document.getElementsByClassName("tooltip tooltip-static");
        //$('#measure_tool').empty(); 

        for (var i = elem.length - 1; i >= 0; i--) {
          elem[i].remove();
        }
      }
      add_draw_Interaction();
    };

    function clear_all() {
      document.getElementById('map').style.height = '96%';
      document.getElementById('table_data').style.height = '0%';
      map.updateSize();
      $('#table').empty();
      //$('#table1').empty();
      if (geojson) { geojson.getSource().clear(); map.removeLayer(geojson); }
      if (featureOverlay) { featureOverlay.getSource().clear(); map.removeLayer(featureOverlay); }
      map.removeInteraction(draw);
      if (draw1) { map.removeInteraction(draw1); }
      if (vector1) { vector1.getSource().clear(); }

      if (vectorLayer) { vectorLayer.getSource().clear(); }
      map.removeOverlay(helpTooltip);
      if (measureTooltipElement) {
        var elem = document.getElementsByClassName("tooltip tooltip-static");
        for (var i = elem.length - 1; i >= 0; i--) {
          elem[i].remove();
        }
      }
      map.un('singleclick', getinfo);
      overlay.setPosition(undefined);
      closer.blur();
      map.un('click', highlight);
    }

  </script>
</body>

</html>